<?php

/**
 * category_levels actions.
 *
 * @package    master_directory
 * @subpackage category_levels
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class category_levelsActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
  	$this->form = new LevelForm();
  	
    //$this->master_directories = $this->filterCategoryDirectories();

  	$this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id")));
  	
  	$this->categories = array();
  	
  	$categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->directory->getId());
  	
  	foreach ($categories as $category){
  		array_push($this->categories, $category);
  	}
  	
    //$this->categories = $this->retreiveActiveCategories();
   // $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->directory->getId());
    

    $this->levels = count($this->categories) > 0 ? $this->retreiveCategoryLevels($this->categories[0]) : array();
    
    $this->root_level =  count($this->categories) > 0 ? Doctrine_Core::getTable('Level')->getRootLevel($this->categories[0]->getId()) : null;
    
    
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->level = Doctrine_Core::getTable('Level')->find(array($request->getParameter('id')));
    $this->forward404Unless($this->level);
    $this->form = new LevelForm($this->level);
    //$this->master_directories = $this->filterCategoryDirectories();  

    $this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id")));
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->form->getObject()->getCategory()->getMasterDirectoryId());
    $this->levels = $this->retreiveCategoryLevels($this->form->getObject()->getCategory());
    
    return $this->renderPartial('category_level', array('form' => $this->form, 'categories' => $this->categories, 'levels' => $this->levels, 'directory' => $this->directory)); 
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new LevelForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $form = new LevelForm();

    $this->processForm($request, $form);
    
    //$this->master_directories = $this->filterCategoryDirectories();
    $this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id"))); 
    
    //$this->categories = $this->retreiveActiveCategories();
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($form->getObject()->getCategory()->getMasterDirectoryId());

    $this->levels = $this->retreiveCategoryLevels($form->getObject()->getCategory());
    
    $this->root_level = Doctrine_Core::getTable('Level')->getRootLevel($form->getObject()->getCategoryId());
    
    
   // $this->root_level = $result_set[0];    
    
    $level = new Level();
    $level->setCategoryId($form->getObject()->getCategoryId());
   	$level->setParentId($form->getObject()->getParentId());
    $this->form = new LevelForm($level);
    
    $this->getUser()->setFlash('save_category', 'Level created successfully', false);
    
	$action_str = "Level created ID: " . $form->getObject()->getId();
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));    
    
    return $this->renderPartial('category_levels_container', array('form' => $this->form, 'categories' => $this->categories, 'levels' => $this->levels, 'root_level' => $this->root_level, 'directory' => $this->directory));

  }
  
  
  
  public function executeLoadCategoryData(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $level = new Level();
    $level->setCategoryId($request->getParameter('id'));
   	//$level->setParentId($form->getObject()->getParentId());
    $this->form = new LevelForm($level);
    //$this->processForm($request, $form);
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->form->getObject()->getCategory()->getMasterDirectoryId());
    
    //$this->categories = $this->retreiveActiveCategories();

    $this->levels = $this->retreiveCategoryLevels($this->form->getObject()->getCategory());
    
    $this->root_level = Doctrine_Core::getTable('Level')->getRootLevel($this->form->getObject()->getCategoryId());
    
   //$this->master_directories = $this->filterCategoryDirectories();

    $this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id")));
    
   // $this->root_level = $result_set[0];    
    
    
    
    return $this->renderPartial('category_levels_container', array('form' => $this->form, 'categories' => $this->categories, 'levels' => $this->levels, 'root_level' => $this->root_level, 'directory' => $this->directory));

  }  

  
  public function executeLoadCategories(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($request->getParameter('directory_id'));

    $level = new Level();
    $level->setCategoryId($this->categories[0]->getId());
   	//$level->setParentId($form->getObject()->getParentId());
    $this->form = new LevelForm($level);
    //$this->processForm($request, $form);
    
    
    //$this->categories = $this->retreiveActiveCategories();

    $this->levels = $this->retreiveCategoryLevels($this->categories[0]);
    
    $this->root_level = Doctrine_Core::getTable('Level')->getRootLevel($this->categories[0]->getId());
    
    $this->master_directories = $this->filterCategoryDirectories(); 
    
   // $this->root_level = $result_set[0];    
    
    
    
    return $this->renderPartial('category_levels_container', array('form' => $this->form, 'categories' => $this->categories, 'levels' => $this->levels, 'root_level' => $this->root_level, 'master_directories' => $this->master_directories));

  }  

  
  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($level = Doctrine_Core::getTable('Level')->find(array($request->getParameter('id'))), sprintf('Object level does not exist (%s).', $request->getParameter('id')));
    $this->form = new LevelForm($level);
  }

  public function executeUpdate(sfWebRequest $request)
  {
  	
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($level = Doctrine_Core::getTable('Level')->find(array($request->getParameter('id'))), sprintf('Object level does not exist (%s).', $request->getParameter('id')));
    $form = new LevelForm($level);
    
    $previous_name = $level->getName();

    $this->processForm($request, $form);
    
    $new_name = $level->getName();
    
    $category = $level->getCategory();
    
    if($previous_name != $new_name){
    	$templates = array();
  		$template2levels = $level->getTemplate2Level();
  		$upper_levels = $level->getUpperLevel();
  		$side_levels = $level->getSideLevel();
  		
  		foreach ($template2levels as $template2level) {
  			array_push($templates, $template2level->getTemplate());
  			$t2l_name_arr = explode(".", $template2level->getName());
  			//$template2level->setName(str_replace($previous_name, $new_name, $template2level->getName()));
  			$template2level->setName($t2l_name_arr[0] . "." .$new_name);
  			$template2level->save();
  			
  			$generated_uppers = $template2level->getUpperLevel();
  			foreach ($generated_uppers as $generated_upper) {
  				$upper_name_arr = explode(".", $generated_upper->getName());
  				$upper_name_arr[1] = $new_name;
  				$upper_name_replaced = "";
  				foreach ($upper_name_arr as $upper_name) {
  					$upper_name_replaced .= $upper_name . ".";
  				}
  				$upper_name_replaced = substr($upper_name_replaced, 0, strlen($upper_name_replaced) - 1);
  				//$generated_upper->setName(str_replace($previous_name, $new_name, $generated_upper->getName()));
  				$generated_upper->setName($upper_name_replaced);
  				$generated_upper->save();
  			}
  			
  			$generated_sides = $template2level->getSideLevel();
  			foreach ($generated_sides as $generated_side) {
  				
  				$side_name_arr = explode(".", $generated_side->getName());
  				$side_name_arr[1] = $new_name;
  				$side_name_replaced = "";
  				foreach ($side_name_arr as $side_name) {
  					$side_name_replaced .= $side_name . ".";
  				}
  				$side_name_replaced = substr($side_name_replaced, 0, strlen($side_name_replaced) - 1);
  				
  				//$generated_side->setName(str_replace($previous_name, $new_name, $generated_side->getName()));
  				$generated_side->setName($side_name_replaced);
  				$generated_side->save();
  			}
  			
  		}
  		foreach ($upper_levels as $upper_level) {
  			array_push($templates, $upper_level->getTemplate2Level()->getTemplate());
  			$more_uppers = $upper_level->getTemplate2Level()->getUpperLevel();
  			foreach ($more_uppers as $upper) {

  				$upper_name_arr = explode(".", $upper->getName());
  				$upper_name_replaced = $upper_name_arr[0] . ".";
  				for ($upper_index = 1; $upper_index < count($upper_name_arr); $upper_index++) {
  					$piece = ($upper_name_arr[$upper_index] == $previous_name) ? $new_name : $upper_name_arr[$upper_index];
  					$upper_name_replaced .= $piece . ".";
  				}
  				
  				$upper_name_replaced = substr($upper_name_replaced, 0, strlen($upper_name_replaced) - 1);
  				
	  			//$upper->setName(str_replace($previous_name, $new_name, $upper->getName()));
	  			$upper->setName($upper_name_replaced);
	  			
	  			$upper->save();
  			}
  		}
  		//TODO: replace sides the same way as upper
  		foreach ($side_levels as $side_level) {
  			
  			array_push($templates, $side_level->getTemplate2Level()->getTemplate());
  			$more_sides = $side_level->getTemplate2Level()->getSideLevel();
  			foreach ($more_sides as $side) {

  				$side_name_arr = explode(".", $side->getName());
  				$side_name_replaced = $side_name_arr[0] . ".";
  				for ($side_index = 1; $side_index < count($side_name_arr); $side_index++) {
  					$piece = ($side_name_arr[$side_index] == $previous_name) ? $new_name : $side_name_arr[$side_index];
  					$side_name_replaced .= $piece . ".";
  				}
  				
  				$side_name_replaced = substr($side_name_replaced, 0, strlen($side_name_replaced) - 1);
  				
	  			//$side_level->setName(str_replace($previous_name, $new_name, $side_level->getName()));
	  			$side->setName($side_name_replaced);
	  			
	  			$side->save();
  			}
  			
  			/*array_push($templates, $side_level->getTemplate2Level()->getTemplate());
  			$side_level->setName(str_replace($previous_name, $new_name, $side_level->getName()));
  			$side_level->save();*/
  		}
  		
  		foreach ($templates as $template) {
  			$contents = $template->getTemplateContent();
  			foreach ($contents as $content) {
  				$content_str = $content->getTheContent();
  				
	  			$matchPattern = "/#%#(.*?)#%#/";
			
				$variables_str = array();
				
				if (preg_match_all ( $matchPattern, $content_str, $matches )) {
					$variables_str = $matches[0];
					$variables_names = $matches[1];
					$variables_names = array_unique($variables_names);
					//foreach ($variables_str as $variable_str) {
					foreach ($variables_names as $variable_name) {
						$variable_name_arr = explode(".", $variable_name);
						if($variable_name_arr[0] ==  $category->getName()){
							
							$name_replaced = $variable_name_arr[0] . ".";
			  				for ($index = 1; $index < count($variable_name_arr); $index++) {
			  					$piece = ($variable_name_arr[$index] == $previous_name) ? $new_name : $variable_name_arr[$index];
			  					$name_replaced .= $piece . ".";
			  				}
			  				
			  				$name_replaced = substr($name_replaced, 0, strlen($name_replaced) - 1);
							
							//$variable_str_replaced = str_replace($previous_name, $new_name, $variable_str);
			  				//$content->setTheContent(str_replace($variable_str, $variable_str_replaced, $content->getTheContent()));
			  				$content->setTheContent(str_replace("#%#".$variable_name."#%#", "#%#".$name_replaced."#%#", $content->getTheContent()));
						}
						/*if(strpos($variable_str, $category->getName()) !== false && strpos($variable_str, $new_name) === false){
							$variable_str_replaced = str_replace($previous_name, $new_name, $variable_str);
			  				$content->setTheContent(str_replace($variable_str, $variable_str_replaced, $content->getTheContent()));
						}*/
					}
	  				$content->save();
				}
  			}
  		}
    }
    
    
    //$this->categories = $this->retreiveActiveCategories();
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($form->getObject()->getCategory()->getMasterDirectoryId());

    $this->levels = $this->retreiveCategoryLevels($form->getObject()->getCategory());
    
    $this->root_level = Doctrine_Core::getTable('Level')->getRootLevel($form->getObject()->getCategoryId());
    
    //$this->master_directories = $this->filterCategoryDirectories();
    $this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id"))); 
    
    //$this->root_level = $result_set[0];

   	$level = new Level();
    $level->setCategoryId($form->getObject()->getCategoryId());
    $level->setParentId($form->getObject()->getParentId());
    
    $this->form = new LevelForm($level);
    
	$action_str = "Level updated ID: " . $form->getObject()->getId();
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));      
    
    $this->getUser()->setFlash('save_category', 'Level created successfully', false);
    return $this->renderPartial('category_levels_container', array('form' => $this->form, 'categories' => $this->categories, 'levels' => $this->levels, 'root_level' => $this->root_level, 'directory' => $this->directory));
  }

  public function executeDelete(sfWebRequest $request)
  {
    //$request->checkCSRFProtection();

    $this->forward404Unless($level = Doctrine_Core::getTable('Level')->find(array($request->getParameter('id'))), sprintf('Object level does not exist (%s).', $request->getParameter('id')));
    
    //Doctrine_Core::getTable('Level')->deleteChildren($level);
    $directory = $level->getCategory()->getMasterDirectory();
    
    $the_table = Doctrine_Core::getTable ( 'Level' );
	$the_table->setChildren();
	$the_table->getCategoryChildrenList($level);
	$involved_levels = $the_table->getChildren();
	
	
  foreach ($involved_levels as $level) {
  		//echo 'level id:' . $level->getId() .' <br>';
  		
  		//templates
  		$templates = array();
  		$template2levels = $level->getTemplate2Level();
  		$upper_levels = $level->getUpperLevel();
  		$side_levels = $level->getSideLevel();
  		
  		foreach ($template2levels as $template2level) {
  			array_push($templates, $template2level->getTemplate());
  		}
  		foreach ($upper_levels as $upper_level) {
  			array_push($templates, $upper_level->getTemplate2Level()->getTemplate());
  		}
  		foreach ($side_levels as $side_level) {
  			array_push($templates, $side_level->getTemplate2Level()->getTemplate());
  		}
  		
  		$templates = array_unique($templates);
  			
  		foreach ($templates as $template) {
  			
  			//echo 'tplt id:' . $template->getId() .' <br>';
  			
  			$remainingTemplate2levels = $template->getTemplate2Level();
  			foreach ($remainingTemplate2levels as $remainingTemplate2level) {
	  			$sideLevels = $remainingTemplate2level->getSideLevel();
	  			foreach ($sideLevels as $sideLevel) {
	  				$sideLevel->delete();
	  			}
	  			$upperLevels = $remainingTemplate2level->getUpperLevel();
	  			foreach ($upperLevels as $upperLevel) {
	  				//echo 'deleting upper <br>';
	  				$upperLevel->delete();
	  			}
	  			
	  			$remainingTemplate2level->delete();
  			}
  			
  			if($template->getId() == $directory->getHomeTemplateId()){
  				$directory->setHomeTemplateId(null);
  				$directory->save();
  			}
  			$directory_search = Doctrine_Core::getTable('SearchConfiguration')->getByDirectory($directory->getId());
  			foreach ($directory_search as $search) {
  				if($search->getTemplateId() == $template->getId()){
	  				$search->delete();
  				}
  			}
  			
  			$template_contents = $template->getTemplateContent();
  			foreach ($template_contents as $template_content) {
  				$template_content->delete();
  			}
  			$templates_with_footer = Doctrine_Core::getTable('Template')->getTemplatesWithTemplateFooter($template->getId());
  			foreach ($templates_with_footer as $template_with_footer) {
  				$template_with_footer->setFooterId(null);
  				$template_with_footer->save();
  			}
  			$template->delete();
  		}
  		
  		//listings
  		$listings = array();
  		$listing2levels = $level->getListing2level();
  		foreach ($listing2levels as $listing2level) {
  			array_push($listings, $listing2level->getListing());
  			$listing2level->delete();
  		}
  		$listings = array_unique($listings);
  		foreach ($listings as $listing) {
  			$fields = $listing->getListFields();
  			foreach ($fields as $field) {
  				$selections = $field->getListingSelection();
  				foreach ($selections as $selection) {
  					$selection2contents = $selection->getListingSelection2categoryContent();
  					foreach ($selection2contents as $selection2content) {
  						$selection2content->delete();
  					}
  					$selection->delete();
  				}
	  			$field->delete();
  			}
  			$listing->delete();
  		}
  		
  		//contents at the same level
  		$the_table = Doctrine_Core::getTable ( 'Level' );
		$the_table->setTreePath();
		$the_table->findTreePath($level);
		$tree_path = $the_table->getTreePath();
		$category_content = Doctrine_Core::getTable('CategoryContent');
		$category_content->setContentArr();				
		$contents = Doctrine_Core::getTable('CategoryContent')->getContentsByTreePath($tree_path, $level->getCategory()->getId());
		foreach ($contents as $content) {
			$content->delete();
		}
		
  	}
  	foreach ($involved_levels as $level) {
  		$level->delete();
  	}
    
    
    $this->form = new LevelForm();
  	
    //$this->categories = $this->retreiveActiveCategories();
    //$this->master_directories = $this->filterCategoryDirectories();

    $this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id"))); 
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->directory->getId());

    $this->levels = $this->retreiveCategoryLevels($this->categories[0]);
    
    $this->root_level = Doctrine_Core::getTable('Level')->getRootLevel($this->categories[0]->getId());
    
	$action_str = "Level deleted ID: " . $request->getParameter('id');
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));         
    
    $this->getUser()->setFlash('save_category', 'Level deleted successfully', false);
    return $this->renderPartial('category_levels_container', array('form' => $this->form, 'categories' => $this->categories, 'levels' => $this->levels, 'root_level' => $this->root_level, 'directory' => $this->directory));

   // $this->redirect('category_levels/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {

  	
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    
     
    
   if ($form->isValid())
    {
      $level = $form->save();

    }
    
  }
  
  protected function retreiveActiveCategories(){
    $q = Doctrine_Core::getTable('Category')->createQuery('a');
    $q->andWhere('a.deleted = 0');
    return $q->execute();
  }  
  
  protected function retreiveCategoryLevels($category){
    $q = Doctrine_Core::getTable('Level')->createQuery('a');
    $q->andWhere('a.category_id = ?',$category->getId());
    $q->andWhere('a.deleted = 0');
    return $q->execute();
  }  
  
 protected function filterCategoryDirectories(){
  	$directories_with_categories = array();
  	$levels = Doctrine_Core::getTable('Level')->loadAll();
  	foreach ($levels as $level){
  		$directory = $level->getCategory()->getMasterDirectory();
  		if($directory->getDeleted() == 0){
	  		array_push($directories_with_categories, $level->getCategory()->getMasterDirectory());
  		}
  	}
  	
  	return array_unique($directories_with_categories);
  }
  
  
}
